/**
 * 全站http配置
 *
 * axios参数说明
 * isSerialize是否开启form表单提交
 * isToken是否需要token
 */
import axios from 'axios'
//import { useRouter } from 'vue-router'
//import router from '@/router/router'
import { serialize } from '../util/util'
import { getToken } from '../util/auth'
import { Notify } from 'vant'
import website from '../config/website'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { Base64 } from 'js-base64'

// axios.defaults.baseURL = 'http://106.13.231.246'
axios.defaults.baseURL = '/'

axios.defaults.timeout = 1000 * 60 * 10

const whiteUrlList = ['api/blade-user/info']

//返回其他状态吗
axios.defaults.validateStatus = function (status) {
  return status >= 200 && status <= 500 // 默认的
}
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true
// NProgress Configuration
NProgress.configure({
  showSpinner: false,
})
//HTTPrequest拦截
axios.interceptors.request.use(
  (config: any) => {
    NProgress.start() // start progress bar
    const meta = config.meta || {}
    const isToken = meta.isToken === false
    config.headers['Authorization'] = `Basic ${Base64.encode(
      `${website.clientId}:${website.clientSecret}`
    )}`
    if (getToken() && !isToken) {
      config.headers['Blade-Auth'] = 'bearer ' + getToken() // 让每个请求携带token--['Authorization']为自定义key 请根据实际情况自行修改
    }
    //headers中配置serialize为true开启序列化
    if (config.method === 'post' && meta.isSerialize === true) {
      config.data = serialize(config.data)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)
//HTTPresponse拦截
axios.interceptors.response.use(
  (res) => {
    NProgress.done()
    const status: any = res.data.code || 200
    const statusWhiteList: any[] = website.statusWhiteList || []
    const message = res.data.msg || '未知错误'
    //如果在白名单里则自行catch逻辑处理
    if (statusWhiteList.includes(status)) return Promise.reject(res)
    //如果是401则跳转到登录页面
    if (status === 401) {
      let url = ''
      if (location.search) {
        url = `${location.origin}${location.pathname}#/login${location.search}`
      } else {
        const query = location.href.split('?')[1] || ''
        url = `${location.origin}${location.pathname}#/login?${query}`
      }
      location.replace(url)
    }
    // 如果请求为非200否者默认统一处理
    if (status !== 200) {
      const bool = whiteUrlList.some((url) => res.config.url?.includes(url))
      if (!bool && message) {
        Notify({ type: 'danger', message: message })
      }

      return Promise.reject(new Error(message))
    }
    return res
  },
  (error) => {
    NProgress.done()
    return Promise.reject(new Error(error))
  }
)

export default axios
